package com.zzy.utils.exception;

import com.zzy.utils.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

import static com.zzy.utils.exception.BizCodeEnume.*;

/**
 * @Author kazu
 * @Date 2023/2/6 0:43
 * @Version 1.0
 *
 * 集中处理所有异常
 */
@SuppressWarnings({"all"})
@Slf4j
@RestControllerAdvice(basePackages = {"com.zzy"})
public class CastomExceptionHandler {
	
	
	@ExceptionHandler(value = {MethodArgumentNotValidException.class})
	public R handlerVaildException(MethodArgumentNotValidException e) {
		log.error("数据校验出现问题{}, 异常类型{}", e.getMessage(), e.getClass());
		BindingResult result = e.getBindingResult();
		HashMap<String, Object> map = new HashMap<>();
		result.getFieldErrors().forEach((it) -> {
			map.put(it.getField(), it.getDefaultMessage());
		});
		return R.error(VALID_EXCEPTION.getCode(), VALID_EXCEPTION.getMsg())
				.put("error", map);
	}
	
	@ExceptionHandler(value = {Throwable.class})
	public R handleExecption(Exception e) {
		System.out.println("----------------------------------------------------------");
		System.out.println(UNKNOWN_EXCEPTION.getCode());
		System.out.println(UNKNOWN_EXCEPTION.getMsg());
		e.printStackTrace();
		System.out.println("----------------------------------------------------------");
		return R.error(UNKNOWN_EXCEPTION.getCode(), UNKNOWN_EXCEPTION.getMsg());
	}
	
	
}
